import { ConfigService } from '@nestjs/config'

/**
 * @example
 * chunk([1,2,3,4], 2) => [[1,2], [3,4]]
 */
export function chunk<T>(arr: T[], size: number) {
  const result: T[][] = [[]]
  arr.forEach((item, i) => {
    if ((i + 1) % size === 0) {
      result[result.length - 1].push(item)
      if (i !== arr.length - 1) result.push([])
    } else {
      result[result.length - 1].push(item)
    }
  })

  return result
}

const regExp = {
  fileExt: /(\.(?!\d)[a-zA-Z\d]+)$/
}

/**
 * 获取文件后缀
 *
 * @export
 * @param {string} file
 * @returns
 */
export function fileExt(file: string) {
  const ext = file.match(regExp.fileExt)
  return ext && ext[0]
}

/**
 * 通过带后缀文件名 获取 文件名(不带后缀)
 */
export function fileName(name: string) {
  return name.replace(regExp.fileExt, '')
}

export function domain(configService: ConfigService<AppConfig>) {
  const host = configService.get('HTTP_HOST')
  const port = configService.get('HTTP_PORT')

  return `${host}:${port}`
}
